package xyz.hubery.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import xyz.hubery.domain.CashRecharge;
import xyz.hubery.domain.CoinRecharge;
import xyz.hubery.dto.UserDTO;
import xyz.hubery.feign.UserFeign;
import xyz.hubery.mapper.CoinRechargeMapper;
import xyz.hubery.service.CoinRechargeService;

@Service
public class CoinRechargeServiceImpl extends ServiceImpl<CoinRechargeMapper, CoinRecharge> implements CoinRechargeService {


    @Autowired
    private UserFeign userFeign;

    @Override
    public Page<CoinRecharge> findPage(Long userId, String userName, String mobile, Byte status, Integer numMin, Integer numMax, String startTime, String endTime, Page<CoinRecharge> page) {


        page.addOrder(OrderItem.desc("last_update_time"));
        LambdaQueryWrapper<CoinRecharge> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(userId != null, CoinRecharge::getUserId, userId);
        wrapper.eq(status != null, CoinRecharge::getStatus, status);
        wrapper.between(numMin != null && numMax != null, CoinRecharge::getAmount, numMin, numMax);
        wrapper.between(startTime != null && endTime != null, CoinRecharge::getCreated, startTime, endTime);

        Page<CoinRecharge> coinRechargePage = page(page, wrapper);
        List<Long> userIds = new ArrayList<>();
        // 获取用户id列表
        if (userId != null) {  // 直接根据userId查询
            userIds.add(userId);
        } else { // 提取用户id列表
            userIds = coinRechargePage.getRecords().stream().map(CoinRecharge::getUserId).distinct().collect(Collectors.toList());
        }
        if (CollectionUtils.isEmpty(userIds)) {
            return coinRechargePage;
        }
        // 远程调用根据用户id列表查询用户信息
        List<UserDTO> userDTOList = userFeign.getBasicUserInfo(userIds);
        // 转换为map结构
        Map<Long, UserDTO> userDTOMap = userDTOList.stream().collect(Collectors.toMap(UserDTO::getId, user -> user));
        // 提取出符合条件的充值记录
        List<CoinRecharge> filteredRecords = new ArrayList<>();
        Set<Long> filterIds = new HashSet<Long>();
        for (UserDTO userDTO : userDTOList) {
            boolean match = true;
            if (!StringUtils.isEmpty(userName) && !userDTO.getUsername().contains(userName)) { //根据用户名进行匹配
                match = false;
            }
            if (!StringUtils.isEmpty(mobile) && !userDTO.getMobile().contains(mobile)) { //根据手机号进行匹配
                match = false;
            }
            if (match) {
                filterIds.add(userDTO.getId());
            }
        }

        List<CoinRecharge> records = coinRechargePage.getRecords();
        for (CoinRecharge record : records) {
            if (filterIds.contains(record.getUserId())) {
                // 填充用户信息
                UserDTO userDTO = userDTOMap.get(record.getUserId());
                record.setUsername(userDTO.getUsername());
                filteredRecords.add(record);
            }
        }

        // 替换为过滤后的记录
        coinRechargePage.setRecords(filteredRecords);
        coinRechargePage.setTotal(filteredRecords.size());
        return coinRechargePage;


    }


    @Override
    public Page<CoinRecharge> findCoinRechargePage(Long userId, Long coinId, Page<CoinRecharge> page) {
        return page(page, new LambdaQueryWrapper<CoinRecharge>()
                .eq(CoinRecharge::getUserId, userId)
                .eq(coinId != null, CoinRecharge::getCoinId, coinId));
    }
}